import os
from src.formats.MBTTiles.readMBT import readTileFromMBT


def getSrcPath():

    return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))


# tpk二维地图打包文件瓦片管理类
class MBTTilesManager:
    def __init__(self, filePath):
        print('init GetTile')
        self.srcPath = getSrcPath()
        # 打包文件路径
        # 若在此文件中直接建立一个对数据库的连接，即多次http请求只公用一个数据库连接甚至是游标可能会出现冲突，甚至是程序异常退出
        # 经过测试一次完成的从文件中获取瓦片的操作仅需要几毫秒，所以每次请求都进行一次完整的数据库读取操作。
        self.filePath = filePath

        self.WMTSCapabilities = self.readWMTSCapabilities()
        self.TMSRootXML = self.readTMSRootXML()
        self.TMSBasemapXML = self.readTMSBasemapXML()
        self.TMSTilemapserviceXML = self.readTMSTilemapserviceXML()

    # 直接返回图片数据
    def getTileFromLRC(self, level, row, column, tilesize=256):
        if not tilesize:
            tilesize = 256

        # mbtiles按照OSGeo的TMS规范来生成和组织的地图瓦片
        # 因mbtiles行列号是TMS标准，所以在此进行修正
        i = int((int(tilesize)/256)-1)
        row = int(2**(level - i) - row - 1)
        img = []
        try:
            img = readTileFromMBT(self.filePath, level, row, column)

        except Exception as e:
            print(e)

        finally:
            length = len(img)

            if length == 1:
                return {
                    "level": level,
                    "row": row,
                    "column": column,
                    "imgData": img[0][0]
                }
            else:
                # 这里抛出错误，直接让上层引发404
                raise Exception
                # return {
                #     "level": level,
                #     "row": row,
                #     "column": column,
                #     "imgData": []
                # }

    def readWMTSCapabilities(self):
        path = self.srcPath + '/conf/wmts/getcapabilities.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def readTMSRootXML(self):
        path = self.srcPath + '/conf/tms/root.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def readTMSBasemapXML(self):
        path = self.srcPath + '/conf/tms/basemap.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def readTMSTilemapserviceXML(self):
        path = self.srcPath + '/conf/tms/tilemapservice.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def __del__(self):
        print('bye')

# man = TilesManager("E:/data/arcgis/tpk/guangming1_2/0200.tpk")
# print('data', man.getTileFromLRC(13, 3058, 13372))
